package com.tieshan.smartwindow.service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.os.SystemClock
import com.hjq.toast.ToastUtils
import com.tencent.mmkv.MMKV
import com.tieshan.smartwindow.other.MMKVConfig
import com.tieshan.smartwindow.other.pisutil.UDPData
import com.tieshan.smartwindow.other.pisutil.UDPDataUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
import java.net.DatagramPacket
import java.net.InetAddress
import java.net.MulticastSocket
import java.net.SocketException
import java.util.*
import java.util.concurrent.*


/**
 * author : Hleo
 * time   : 2022/2/9
 * desc   : pis接收服务
 */
class PisService : Service() {
    private val ip = "225.0.1.4" //组播地址
    private val port = 8880 //指定数据接收端口

    private var multicastSocket: MulticastSocket? = null

    @Volatile
    private var lastReceiveMessageTime = 0L

    private var isDestroy = false

    private var mBinder: SimpleBinder = SimpleBinder()
    var index = 0

    override fun onBind(intent: Intent?): IBinder {
        return mBinder
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_NOT_STICKY
    }

    override fun onUnbind(intent: Intent): Boolean {
        return false
    }

    inner class SimpleBinder : Binder() {
        val service: PisService
            get() = this@PisService
    }

    override fun onCreate() {
        super.onCreate()
        isDestroy = false
        GlobalScope.launch(Dispatchers.Main) {
            while (isDestroy.not()) {
                delay(5000)
                if (SystemClock.elapsedRealtime() - lastReceiveMessageTime > 5000) {
                    pisMessageListener()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        isDestroy = true
    }

    fun pisMessageListener() {
        try {
            val group = InetAddress.getByName(ip)
            multicastSocket?.close()
            multicastSocket = MulticastSocket(port)
            val socket = multicastSocket!!
            socket.joinGroup(group)
            GlobalScope.launch(Dispatchers.IO) {
                delay(1000)
                val buf = ByteArray(1024)
                while (socket.isClosed.not()) {
                    try {
                        val packet = DatagramPacket(buf, 0, buf.size)
                        multicastSocket?.receive(packet)
                        lastReceiveMessageTime = SystemClock.elapsedRealtime()
                            //数据传输以后再重置
                            index = 0
                            pisMessage(packet.data!!)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        delay(1000)
                    }
                }
            }
        } catch (e: SocketException) {
            index++
            ///如果没有重启，则发送重启指令,5分钟以后进行重启。重启以后将存的数据进行重置
            if (index >= 30) {
                ToastUtils.show("PIS数据获取失败，错误信息=${e.toString()},index=$index")
                index = 0
                val bean = UDPData()
                bean.isReboot = true
                EventBus.getDefault().post(bean)
            }
        }
    }

    private fun pisMessage(data: ByteArray) {
        try {
            val bean = UDPDataUtil.dealWithData(data) ?: return
            EventBus.getDefault().post(bean)
        } catch (e: Exception) {
            Timber.d("Exception=${e}")
        }
    }

}